package edu.uwm.cs552;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import edu.uwm.cs552.gfx.SVGImageCreator;

public class HexBoardDialog extends JDialog implements ActionListener {

	/**
	 * Keep Eclipse Happy 
	 */
	private static final long serialVersionUID = 1L;
	
	private JTextField urlField = new JTextField(40);
	private JTextField widthField = new JTextField(5);
	private JTextField heightField = new JTextField(5);
	private JButton cancelButton = new JButton("Cancel");
	private JButton okButton = new JButton("OK");
	
	private HexBoard result = null;
	
	public HexBoardDialog(JFrame owner) {
		super(owner, "Create Hex Board", true);
		JPanel urlPanel = new JPanel();
		urlPanel.add(new JLabel("Background URL:"));
		urlPanel.add(urlField);
		JPanel boundsPanel = new JPanel();
		boundsPanel.add(new JLabel("width:"));
		boundsPanel.add(widthField);
		boundsPanel.add(new JLabel("height:"));
		boundsPanel.add(heightField);
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(cancelButton);
		buttonPanel.add(okButton);
		cancelButton.addActionListener(this);
		okButton.addActionListener(this);
		JPanel content = new JPanel();
		content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
		content.add(urlPanel);
		content.add(boundsPanel);
		content.add(buttonPanel);
		add(content);
		setSize(600,200);
	}
	
	public void actionPerformed(ActionEvent arg0) {
		if (arg0.getSource() == cancelButton) {
			result = null;
		} else if (arg0.getSource() == okButton) {
			float w = textFieldFloat("Width",widthField);
			if (w <= 0) return;
			float h = textFieldFloat("Height",heightField);
			if (h <= 0) return;
			String url = urlField.getText();
			if (url.trim().equals("")) {
				result = new HexBoard(null,w,h);
			} else {
				SVGImageCreator background;
				try {
					background = new SVGImageCreator(new URL(url));
				} catch (IOException ex) {
					JOptionPane.showMessageDialog(this,ex.getMessage(), "URL Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				result = new HexBoard(background,w,h);
			}
		}
		setVisible(false);		
	}
	
	private float textFieldFloat(String name, JTextField tf) {
		float result;
		try {
			result = Float.parseFloat(tf.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "Format Error", JOptionPane.ERROR_MESSAGE);
			return -1;
		}
		if (result <= 0) {
			JOptionPane.showMessageDialog(this, name + " must be positive", "Range Error", JOptionPane.ERROR_MESSAGE);
		}
		return result;
	}
	
	public HexBoard getResult() {
		return result;
	}
}
